<?php

namespace app\common\model;

use app\common\model\order\Order;
use app\common\model\user\Level;
use think\Model;

/**
 * 会员余额日志模型
 */
class MoneyLog extends Model
{

    // 表名
    protected $name = 'user_money_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
        'money_text',
        'createtime_text',
    ];
    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getTypeList()
    {
        return ['1' => __('支出'), '2' => __('收入')];
    }
    public function getMoneyTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['source_type']) ? $data['source_type'] : '');
        $list = $this->getMoneyType();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public static function getMoneyType()
    {
        return [
            100 => '销售提成',
            101 => '订单结算代理回馈收益',
            200 => '管理提成',
            300 => '伯乐津贴',
            400 => '订单结算分红奖收益',
            500 => '余额转赠',
            501 => '余额获赠',
            502 => '余额提现',
            503 => '余额支付（不可提现余额）',
            504 => '余额支付（可提现余额）',
            600 => '管理员变更金额',
            700 => '会员权益值分红',
        ];
    }
    /**
     * Notes:记录会员账户流水，如果变动类型是成长值，且是增加的，则调用更新会员等级方法。该方法应在添加用户账户后调用
     * @author: cjh 2020/12/15 11:49
     * @param int $user_id  用户id
     * @param float $amount 变动数量
     * @param int $change_type  变动类型：1-减少；2-增加
     * @param int $source_type 来源类型
     * @param string $source_id 来源id
     * @param string $source_sn 来源单号
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function income($user_id, $amount, $change_type, $source_type, $source_sn = '', $interests = 0)
    {
        $user = new User;
        $user = $user->get($user_id);
        if (empty($user)) {
            return false;
        }
        $before = bcadd($user->money, $user->no_money, 2);
        if ($change_type == 1) {
            if ($source_type == 503) {
                $user->setDec('no_money', $amount);
            } else {
                $user->setDec('money', $amount);
            }
            $amount = -$amount;
        } else {
            if ($source_type == 500) {
                $user->setInc('no_money', $amount);
            } else {
                $user->setInc('money', $amount);
            }
        }
        $list =  self::getMoneyType();
        $left_amount = bcadd($user->money, $user->no_money, 2);
        $account_log = new self;
        $data['type'] = $change_type;
        $data['order_sn'] = $source_sn;
        $data['user_id'] = $user_id;
        $data['money'] = $amount ?? 0;
        $data['interests'] = $interests ?? 0;
        $data['before'] = $before ?? 0;
        $data['after'] = $left_amount ?? 0;
        $data['memo'] = isset($list[$source_type]) ? $list[$source_type] : '';
        $data['source_type'] = $source_type;
        $account_log->allowField(true)->save($data);
        return true;
    }


    //订单分佣
    public static function subcommission($pay_money, $uid, $order_sn)
    {
        $user = User::get($uid);
        if ($user->level > 0) {
            return true;
        }
        $order = Order::get(['sn' => $order_sn]);

        ScoreLog::income($user->id, $order->total_points, 2, 300, $order_sn);
        //积分分佣
        if ($user->pid) {
            $first = bcdiv(config('site.first'), 100, 2);
            $firstPoint = bcmul($order->total_points, $first, 2);
            ScoreLog::income($user->pid, $firstPoint, 2, 300, $order_sn);
            $first_user = User::get($user->pid);
            if ($first_user && $first_user->pid) {
                $two = bcdiv(config('site.two'), 100, 2);
                $twoPoint = bcmul($order->total_points, $two, 2);
                ScoreLog::income($first_user->pid, $twoPoint, 2, 300, $order_sn);
                $three_user = User::get($first_user->pid);
                if ($three_user && $three_user->pid) {
                    $three = bcdiv(config('site.three'), 100, 2);
                    $threePoint = bcmul($order->total_points, $three, 2);
                    ScoreLog::income($three_user->pid, $threePoint, 2, 300, $order_sn);
                }
            }
        }
        //直推分佣
        if ($user->pid && $order->state == '1') {
            //分佣比例
            $proportion =  UserGroup::column('id,commission');
            $puser = User::where('id', $user->pid)->find();
            $commission = floatval($proportion[$puser->group_id]);
            if ($commission > 0) {
                $money = bcmul($pay_money,  $commission, 2);
                if ($money > 0) {
                    self::income($puser->id, $money, 2, 100, $order_sn);
                }
            }
        }


        //管理收益
        // if ($user->paren_ids) {
        //     $management = User::whereIn('id', $user->paren_ids)->orderRaw("field(id, $user->paren_ids)")->where('level', '>', 0)->select();
        //     // $lv = array(1 => 0.05, 2 => 0.09, 3 => 0.12, 4 => 0.15, 5 => 0.19, 6 => 0.21);
        //     $lv = Level::column('id,commission');
        //     $por = 0;
        //     foreach ($management as $key => $v) {
        //         if ($v->level > $user->level) {
        //             $comm = $lv[$v->level];
        //             if ($comm > 0) {
        //                 $comm -= $por;
        //                 if ($comm > 0) {
        //                     $managementMoney = bcmul($pay_money,  $comm, 2);
        //                     if ($managementMoney > 0) {
        //                         self::income($v->id, $managementMoney, 2, 200, $order_sn);
        //                     }
        //                     $por += $comm;
        //                 }
        //             }
        //         }
        //         //伯乐奖
        //         if ($v->paren_ids) {
        //             // $bole = User::get($v->pid);
        //             $bole = User::whereIn('id', $v->paren_ids)->orderRaw("field(id, $v->paren_ids)")->select();
        //             foreach ($bole as $key => $v) {
        //                 if ($v->group_id == 4) {
        //                     $boleMoney = bcmul($managementMoney, 0.25, 2);
        //                     self::income($v->id, $boleMoney, 2, 300, $order_sn);
        //                     break;
        //                 }
        //             }
        //         }
        //     }
        // }
    }

    //总裁分红
    public static function dividend()
    {
        $count = self::whereTime('createtime', 'between', [date('Y-12-31'), date('Y-12-31 23:59:59')])->count();
        if ($count) {
            exception('今年已分红');
        }
        $user = User::all(['level' => 7]);
        $totalMoney = Order::where('status', '>', '0')->whereTime('paytime', 'years')->sum('pay_money');
        $commission = Level::where('level', 7)->value('commission');
        foreach ($user as $v) {
            $dividendMoney = bcmul($totalMoney, $commission, 2);
            $uids = User::where("find_in_set({$v->id},paren_ids)")->column('id');
            $sumMoney = Order::where('status', '>', '0')->whereTime('paytime', 'years')->whereIn('id', $uids)->sum('pay_money');
            self::income($v->id, bcmul($dividendMoney, bcdiv($sumMoney, $totalMoney, 2), 2), 2, 400);
        }
    }
}
